var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var page = 1;
var loadingMore = false;
var hasMore = true;
var SDKVersion = '';
var uid = 0;
var cpage = 1;

Page({

  data: {
    util: util,
    ghsData: [],

    authData: '',

    uid: 0,
    token: '',
    picker_arr: [],//picker中range属性值
    picker_index: 0,//picker中value属性值
    id_arr: [],//存储id数组
    result: "",//form提交最终结果
    userV: "",
    phoneV: "",

    org_name: '',
    tc: 0,
    hasData: false,
    footer_curr: ["", "curr"],
    userInfo: {},
    inviteCount: 0,//总邀请人数
    recents: [],
    imgDomain: app.globalData.imgDomain,
    tabCataData: [{ id: 0, title: "今日", subList:[]},
      { id: 1, title: "本周", subList: []},
      { id: 2, title: "本月", subList: []}],
    tabcurrcata: 0,
    subcurrcata: 0,
    subCataData: [{ id: 0, title: "邀请记录"},
    { id: 1, title: "提成"}],
  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    wx.showLoading({
      title: 'loading',
      mask: 'true'
    });

    var that = this;
    var tc = app.get_tc();
    that.setData({
      tc:tc
    })
    var titlename = tc == 1 ? '加盟代銷' : '加盟代销';
    if(util.orgid==20510){
      titlename = tc == 1 ? '會員專區' : 'Member';
    }
    wx.setNavigationBarTitle({
      title: titlename,
    });


    hasMore = true;
    page = 1;

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
      console.log("coloset", color)
    });

    //初始化底部导航
    var b_nav_data = app.getBottomNavData('ghs_list/ghs_list', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        SDKVersion = res.SDKVersion;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          tc: app.get_tc(),
          isIphone_x: isIphone_x,
          screen_h:res.windowHeight,
          wz_item_img_w_1: res.windowWidth - 25
        });
      }
    })

    this.getLoginUserInfo('');


    //获取绑定orgid信息
    app.GetUserInfo(util.orgid, function (res) {
      that.setData({
        org_name: res.uname
      })
    });

    var inviteuid = options.inviteuid;
    //调用应用实例的方法获取全局数据
    app.LoginUserInfo(function (res) {
      //更新数据
      that.setData({
        userInfo: res
      })
      uid = res.uid;
      util.api({
        data: {
          "uid": res.uid,
          "publickey": util.publiccode,
          "ac": "userinfo"
        },
        success: function (responseData) {
          console.log(responseData.data);
          that.setData({
            userinfo: responseData.data
          });
        }
      });
    }, inviteuid);
    hasMore = true;
    cpage = 1;
    
  },

  getLoginUserInfo: function (inviteuid) {
    var that = this;
    //调用应用实例的方法获取全局数据
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token
        })
        that.getAuth(res.uid, res.token);
      } else {
        app.reAuthorize(reGetUserInfo);
        wx.hideLoading();
      }
    }, inviteuid);
  },

  //获取用户认证状态
  getAuth: function (uid, token) {
    var that = this;
    var privatekey = utilMd5.hexMD5(uid + 'getUserAuth' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "getUserAuth",
        uid: uid,
        catatype: '20',
        privatekey: privatekey
      },
      method: 'GET',
      success: function (responseData) {
        var data = responseData.data;
        console.log("获取已提交的认证信息：", data);
        if (data && data.res != false && data.realname) {
          //更新数据
          that.setData({
            authData: data,
            userV: data.realname ? data.realname : '',
            phoneV: data.phone ? data.phone : '',
            invitephoneV: data.invitephone ? data.invitephone : ''
          });
        } else {
          that.setData({
            authData: ''
          });
        }
        //读取供货商信息
        that.loadGHS(1);
      }
    });
  },


  //下拉选项改变值
  bindPickerChange: function (e) {//选项改变触发事件

    this.setData({
      picker_index: e.detail.value
    })
  },


  ////表单提交触发事件
  formSubmit: function (e) {
    app.saveFormId(e.detail.formId);
    if (this.data.authData && this.data.authData.ispay == '0'){
      wx.redirectTo({
        url: '/pages/join_pay/join_pay?coin=50&authtype=20',
      })
      return;
    }

    var that = this;
    var tc = that.data.tc;
    var res = e.detail.value;
    var username = res.username;
    var mobile = res.mobile;
    var invitemobile = res.invitemobile||'';
    var email = res.email ||'';
    var address = res.address ||'';
    var selector = this.data.id_arr[res.selector];

    if (username == "") {
      var contentname = tc == 1 ? '姓名不能為空' : '姓名不能为空';
      wx.showModal({
        title: '提示',
        content: contentname,
        showCancel: false,
      })
      return;
    } else if (mobile == "") {
      var contentmobile = tc == 1 ? '手機號不能為空' : '手机号不能为空';
      wx.showModal({
        title: '提示',
        content: contentmobile,
        showCancel: false,
      })
      return;
    } else if (util.orgid == 18681&&invitemobile == "") {
      var contentinvitemobile = tc == 1 ? '介紹人手機號不能為空' : '介绍人手机号不能为空';
      wx.showModal({
        title: '提示',
        content: contentinvitemobile,
        showCancel: false,
      })
      return;
    } else if (util.orgid == 20510&&email == "") {
      var contentEmail = (tc == -1 ? 'Email required' : tc == 1 ? '郵箱不能為空' : '邮箱不能为空')+'';
      wx.showModal({
        title: '提示',
        content: contentEmail,
        showCancel: false,
      })
      return;
    } else if (selector == "0" || selector == "") {
      var contentselector = tc == 1 ? '請選擇供貨商' : '请选择供货商';
      wx.showModal({
        title: '提示',
        content: contentselector,
        showCancel: false,
      })
      return;
    }

    //提交代理商认证请求
    var ac = 'userauth'
    var privatekey = utilMd5.hexMD5(that.data.uid + 'userauth' + that.data.token);
    if (util.orgid == 18681 || util.orgid == 20510){
      privatekey = utilMd5.hexMD5(that.data.uid + 'userauth2' + that.data.token);
      ac = 'userauth2';
      selector = util.orgid;
    }
    var params = {
      ac: ac,
      uid: that.data.uid,
      realname: username,
      phone: mobile,
      invitephone: invitemobile,
      email: email,
      address: address,
      catatype: "20",
      orgid: selector ? selector:util.orgid,
      selector: selector ? selector : util.orgid,
      privatekey: privatekey
    };
    console.log('代理商认证：', params);
    // return;

    util.api({
      method: "post",
      data: params,
      success: function (responseData) {
        console.log("提交代理商申请信息：", responseData);
        if (responseData.data.res == false) {
          wx.showModal({
            title: '提示',
            content: "介绍人不存在",
            showCancel: false,
          })
        } else {
          var contentsucess = tc == 1 ? '申請資料已提交' : '申请资料已提交';
          that.getAuth(that.data.uid, that.data.token);
          wx.showModal({
            title: '提示',
            content: contentsucess,
            showCancel: false,
            success: function(res){
              // if (res.confirm) {
              //   wx.redirectTo({
              //     url: '/pages/join_pay/join_pay?coin=50&authtype=20',
              //   })
              // }
            }
          })
        }

      },
      fail: function (e) {
        var contentfail = tc == 1 ? '網絡異常,請稍候再試' : '网络异常,请稍候再试';
        wx.showModal({
          title: '提示',
          content: contentfail,
          showCancel: false,
        })

      }
    });
  },


  userNameInput: function (e) {
    this.setData({
      userV: e.detail.value
    })
  },

  userPhoneInput: function (e) {
    this.setData({
      phoneV: e.detail.value
    })
  },
  invitePhoneInput: function (e) {
    this.setData({
      invitephoneV: e.detail.value
    })
  },


  // 读取动态 （近况）
  loadGHS: function (cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghs",
      orgid: util.orgid,
      page: cpage,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("供货商数据：", result);
        if (!result.msg) {
          if (cpage <= 1) {
            that.setData({
              ghsData: result
            });

          } else {

            that.setData({
              ghsData: that.data.ghsData.concat(result)
            });

          }
        } else {
          if (cpage <= 1) {

            that.setData({
              ghsData: []
            });

          }
        }

        var ghsData = that.data.ghsData;
        var picker_arr = ["请选择"];
        var id_arr = ["0"];
        var sel_index = 0;
        var orgid = '0';
        if (that.data.authData && that.data.authData.orgid){
          orgid = that.data.authData.orgid;
        }
        for (var i = 0; i < ghsData.length; i++) {
          var uid = ghsData[i].uid;
          var username = ghsData[i].username;
          if(uid == orgid){
            sel_index = i + 1;
          }
          picker_arr.push(username);
          id_arr.push(uid);
        }
        that.setData({
          picker_arr: picker_arr,
          id_arr: id_arr,
          picker_index: sel_index,
        });

        wx.hideLoading();

      }
    });
  },


  onReady: function () {
    // 页面渲染完成    
    var that = this;
    //获取邀请人数
    that.loadInviteCount();
    //请求当前用户的动态    
    that.loadInviteList(cpage);
    that.loadTakePercentageList();
  },

  //请求邀请总人数
  loadInviteCount: function () {
    var that = this;
    var tabCataData = that.data.tabCataData;
    var tabcurrcata = that.data.tabcurrcata
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "invitecount",
        "uid": uid,
        "time":  tabCataData[tabcurrcata].id+1
      },
      success: function (responseData) {
        console.log(responseData);
        that.setData({
          inviteCount: responseData.data.count ? responseData.data.count : 0
        });
      }
    });
  },

  //请求邀请列表数据
  loadInviteList: function (cpage) {
    var that = this;
    var tabCataData = that.data.tabCataData;
    var tabcurrcata = that.data.tabcurrcata
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "inviteinfo",
        "uid": uid,
        "page": cpage,
        "time":  tabCataData[tabcurrcata].id+1
      },
      success: function (responseData) {
        console.log(responseData);
        if (responseData.res == false) {
          that.setData({
            hasData: false,
            recents: []
          });
        } else {
          var data = responseData.data;
          if (data && data.length > 0) {
            tabCataData[tabcurrcata].subList = tabCataData[tabcurrcata].subList.concat(data)
            that.setData({
              hasData: true,
              recents: that.data.recents.concat(data),
              tabCataData: tabCataData
            });
            console.log("that.data.tabCataData",that.data.tabCataData)
          }

        }
      }
    });
  },

  //加载更多
  loadMore: function () {
    if (hasMore) {
      cpage++;
      this.loadInviteList(cpage);
    }
  },


  changeTabCata: function (e) {
    console.log("Tabcurrcata", e.currentTarget.dataset.current)
    var cur = e.currentTarget.dataset.current;
    if (this.data.tabcurrcata == cur) { return false; }
    else {
      this.setData({
        tabcurrcata: cur
      })
      var that = this;
      that.data.tabCataData[that.data.tabcurrcata].subList = []
      //获取邀请人数
      that.loadInviteCount();
      //请求当前用户的动态
      cpage=1;    
      that.loadInviteList(cpage);

      that.loadTakePercentageList();
    }
  },

  changeSubCata: function (e) {
    console.log("Tabcurrcata", e.currentTarget.dataset.current)
    var cur = e.currentTarget.dataset.current;
    if (this.data.subcurrcata == cur) { return false; }
    else {
      this.setData({
        subcurrcata: cur
      })
    }
  },

  switchTabNav: function (e) {
    console.log("e", e)
    if (e.detail.source == "touch") {
      console.log("e.detail.source")
      this.setData({
        tabcurrcata: e.detail.current,
      });
      var that = this;
      that.data.tabCataData[that.data.tabcurrcata].subList =[]
      //获取邀请人数
      that.loadInviteCount();
      cpage = 1;    
      //请求当前用户的动态    
      that.loadInviteList(cpage);
      that.loadTakePercentageList();


    }
  },

  //提成列表数据
  loadTakePercentageList: function () {
    var that = this;
    var tabCataData = that.data.tabCataData;
    var tabcurrcata = that.data.tabcurrcata
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getgoumaiticheng",
        "uid": uid,
        "num":  tabCataData[tabcurrcata].id+1
      },
      success: function (responseData) {
        console.log(responseData);
        if (responseData.data.res == false) {
          that.setData({
            hasDataTake: false
          });
        } else {
          var data = responseData.data;
          if (data && data.length > 0) {
            tabCataData[tabcurrcata].takePercentageList=data;
            that.setData({
              hasDataTake: true,
              tabCataData: tabCataData
            });
            console.log("that.data.tabCataData", that.data.tabCataData)
          }

        }
      }
    });
    var timestamp = (new Date()).valueOf();
    console.log("timestamp", timestamp)
  },
  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    
    wx.navigateTo({ url: url })
  },


})